<template>
	<div ref="container" class="univer-container"></div>
</template>

<script lang="ts" setup>
// 组件传参的data(要初始化到表格中的数据）
const props = defineProps({
	// workbook data
	data: {
		type: Object,
		require: false,
		default: () => ({}),
	},
	//页脚
	isFooter: {
		type: Boolean,
		require: false,
		default: false,
	},
	//测试传入一个函数
	testFunc: {
		type: Function,
		require: false,
		default: () => ({}),
	},
});

const data = props.data;
import {
	Univer,
	UniverInstanceType,
	Workbook,
	LocaleType,
	IWorkbookData,
} from "@univerjs/core";
import {defaultTheme} from "@univerjs/design";
import {UniverDocsPlugin} from "@univerjs/docs";
import {UniverDocsUIPlugin} from "@univerjs/docs-ui";
import {UniverFormulaEnginePlugin} from "@univerjs/engine-formula";
import {UniverRenderEnginePlugin} from "@univerjs/engine-render";
import {UniverSheetsPlugin} from "@univerjs/sheets";
import {UniverSheetsFormulaPlugin} from "@univerjs/sheets-formula";
import {UniverSheetsUIPlugin} from "@univerjs/sheets-ui";
import {UniverUIPlugin} from "@univerjs/ui";
import {FUniver} from "@univerjs/facade";

// 禅编辑器
import "@univerjs/sheets-zen-editor/lib/index.css";
import {UniverSheetsZenEditorPlugin} from "@univerjs/sheets-zen-editor";
// 超链接
import "@univerjs/sheets-hyper-link-ui/lib/index.css";
import {UniverSheetsHyperLinkPlugin} from "@univerjs/sheets-hyper-link";
import {UniverSheetsHyperLinkUIPlugin} from "@univerjs/sheets-hyper-link-ui";
// 浮动图片
import "@univerjs/drawing-ui/lib/index.css";
import "@univerjs/sheets-drawing-ui/lib/index.css";
import {UniverDrawingPlugin} from "@univerjs/drawing";
import {UniverDrawingUIPlugin} from "@univerjs/drawing-ui";
import {UniverSheetsDrawingPlugin} from "@univerjs/sheets-drawing";
import {UniverSheetsDrawingUIPlugin} from "@univerjs/sheets-drawing-ui";
// 查找与替换
import "@univerjs/find-replace/lib/index.css";
import {UniverFindReplacePlugin} from "@univerjs/find-replace";
import {UniverSheetsFindReplacePlugin} from "@univerjs/sheets-find-replace";
// 筛选
import "@univerjs/sheets-filter-ui/lib/index.css";
import {UniverSheetsFilterPlugin} from "@univerjs/sheets-filter";
import {UniverSheetsFilterUIPlugin} from "@univerjs/sheets-filter-ui";
// 排序
import "@univerjs/sheets-sort-ui/lib/index.css";
import {UniverSheetsSortPlugin} from "@univerjs/sheets-sort";
import {UniverSheetsSortUIPlugin} from "@univerjs/sheets-sort-ui";
// 数据验证
import "@univerjs/sheets-data-validation/lib/index.css";
import {UniverDataValidationPlugin} from "@univerjs/data-validation";
import {UniverSheetsDataValidationPlugin} from "@univerjs/sheets-data-validation";
// 条件格式
import "@univerjs/sheets-conditional-formatting-ui/lib/index.css";
import {UniverSheetsConditionalFormattingPlugin} from "@univerjs/sheets-conditional-formatting";
import {UniverSheetsConditionalFormattingUIPlugin} from "@univerjs/sheets-conditional-formatting-ui";
// 数字格式
import "@univerjs/sheets-numfmt/lib/index.css";
import {UniverSheetsNumfmtPlugin} from "@univerjs/sheets-numfmt";
//评论批注
import "@univerjs/thread-comment-ui/lib/index.css";
import {
	IThreadCommentMentionDataService,
	UniverThreadCommentUIPlugin,
} from "@univerjs/thread-comment-ui";
import {UniverThreadCommentPlugin} from "@univerjs/thread-comment";
import {UniverSheetsThreadCommentBasePlugin} from "@univerjs/sheets-thread-comment-base";
import {UniverSheetsThreadCommentPlugin} from "@univerjs/sheets-thread-comment";

// import ImportCSVButtonPlugin from "./SDK/open-file-csv";
// import SaveDataButtonPlugin from "./SDK/save-data";
// import { onBeforeUnmount, onMounted, ref, toRaw } from "vue";

/**
 *
 * The ability to import locales from virtual modules and automatically import styles is provided by Univer Plugins. For more details, please refer to: https://univer.ai/guides/sheet/advanced/univer-plugins.
 * If you encounter issues while using the plugin or have difficulty understanding how to use it, please disable Univer Plugins and manually import the language packs and styles.
 *
 * 【从虚拟模块导入语言包】以及【自动导入样式】是由 Univer Plugins 提供的能力，详情参考：https://univer.ai/zh-CN/guides/sheet/advanced/univer-plugins
 * 如果您在使用该插件的时候出现了问题，或者无法理解如何使用，请禁用 Univer Plugins，并手动导入语言包和样式
 */
import {zhCN, enUS} from "univer:locales";

const univerRef = ref<Univer | null>(null);
const workbook = ref<Workbook | null>(null);
const container = ref<HTMLElement | null>(null);
let univerAPI: any, _univer: any;
onMounted(() => {
	init(data);
});

onBeforeUnmount(() => {
	destroyUniver();
});

/**
 * Initialize univer instance and workbook instance
 * @param data {IWorkbookData} document see https://univer.ai/typedoc/@univerjs/core/interfaces/IWorkbookData
 */
const init = (data?: {}) => {
	const univer = new Univer({
		theme: defaultTheme,
		locale: LocaleType.ZH_CN,
		locales: {
			[LocaleType.ZH_CN]: zhCN,
			[LocaleType.EN_US]: enUS,
		},
	});
	univerRef.value = univer;

	// 注册插件
	// core plugins
	const isFooter = props.isFooter;
	univer.registerPlugin(UniverRenderEnginePlugin);
	univer.registerPlugin(UniverFormulaEnginePlugin);
	univer.registerPlugin(UniverUIPlugin, {
		container: container.value!,
		header: true,
		//显示页头
		footer: isFooter,
		//显示页脚
		contextMenu: true,
		//显示右键
	});

	// doc plugins
	univer.registerPlugin(UniverDocsPlugin, {
		hasScroll: false,
	});
	univer.registerPlugin(UniverDocsUIPlugin);

	// sheet plugins
	univer.registerPlugin(UniverSheetsPlugin);
	univer.registerPlugin(UniverSheetsUIPlugin);
	univer.registerPlugin(UniverSheetsFormulaPlugin);

	// 禅编辑器
	univer.registerPlugin(UniverSheetsZenEditorPlugin);
	// 超链接
	univer.registerPlugin(UniverSheetsHyperLinkPlugin);
	univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);
	// 浮动图片
	univer.registerPlugin(UniverDrawingPlugin);
	univer.registerPlugin(UniverDrawingUIPlugin);
	univer.registerPlugin(UniverSheetsDrawingPlugin);
	univer.registerPlugin(UniverSheetsDrawingUIPlugin);
	// 查找与替换
	univer.registerPlugin(UniverFindReplacePlugin);
	univer.registerPlugin(UniverSheetsFindReplacePlugin);
	// 筛选
	univer.registerPlugin(UniverSheetsFilterPlugin);
	univer.registerPlugin(UniverSheetsFilterUIPlugin);
	// 排序
	univer.registerPlugin(UniverSheetsSortPlugin);
	univer.registerPlugin(UniverSheetsSortUIPlugin);
	// 数据验证
	univer.registerPlugin(UniverDataValidationPlugin);
	univer.registerPlugin(UniverSheetsDataValidationPlugin);
	// 条件格式
	univer.registerPlugin(UniverSheetsConditionalFormattingPlugin);
	univer.registerPlugin(UniverSheetsConditionalFormattingUIPlugin);
	// 数字格式
	univer.registerPlugin(UniverSheetsNumfmtPlugin);
	// 评论批注
	const mockUser = {
		userID: "mockId",
		name: "MockUser",
		avatar:
			"",
		anonymous: false,
		canBindAnonymous: false,
	};

	class CustomMentionDataService implements IThreadCommentMentionDataService {
		dataSource: Nullable<IThreadCommentMentionDataSource>;
		trigger: string = "@";

		async getMentions(search: string) {
			return [
				{
					id: mockUser.userID,
					label: mockUser.name,
					type: "user",
					icon: mockUser.avatar,
				},
				{
					id: "2",
					label: "User2",
					type: "user",
					icon: mockUser.avatar,
				},
			];
		}
	}

	univer.registerPlugin(UniverThreadCommentPlugin);
	univer.registerPlugin(UniverThreadCommentUIPlugin, {
		overrides: [
			[
				IThreadCommentMentionDataService,
				{useClass: CustomMentionDataService},
			],
		],
	});
	univer.registerPlugin(UniverSheetsThreadCommentBasePlugin);
	univer.registerPlugin(UniverSheetsThreadCommentPlugin);

	//diy plugins
	// univer.registerPlugin(ImportCSVButtonPlugin);
	// univer.registerPlugin(SaveDataButtonPlugin);

	// 利用传的预定义数据data创建工作簿实例
	workbook.value = univer.createUnit<IWorkbookData, Workbook>(
		UniverInstanceType.UNIVER_SHEET,
		data
	);

	// 使用 Facade API;可以通过调用 univerAPI 的方法来使用 Univer,包裹的univer必须完成实例化
	univerAPI = FUniver.newAPI(univer);
	_univer = univer;
};

/**
 * Destroy univer instance and workbook instance
 */
const destroyUniver = () => {
	toRaw(univerRef.value)?.dispose();
	univerRef.value = null;
	workbook.value = null;
};

/**
 * Get workbook data
 */
const getData = () => {
	if (!workbook.value) {
		throw new Error("Workbook is not initialized");
	}
	return workbook.value.save();
};

/**
 * 监听单元格数据变化
 */
const onChangeData = () => {
	let res = univerAPI.onCommandExecuted((command: any) => {
		const {id} = command;
		if (id === "doc.command.insert-text" || id === "doc.command.delete-text") {
			const doc = univerAPI.getActiveDocument();
			if (doc) {
				const snapshot = doc.getSnapshot();
				// console.log(snapshot.body?.dataStream);
				// console.log(snapshot);
				return snapshot.body.dataStream;
			}
		}
	});
	return res;
};

/**
 * 向上层组件返回传参或事件
 */
const expose = {
	getData,
	destroyUniver,
	onChangeData,
};
defineExpose(expose);
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.univer-container {
	width: 100%;
	height: 100%;
	overflow: hidden;
}

/* Also hide the menubar */
:global(.univer-menubar) {
	display: none;
}
</style>
